package com.jwt.interceptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jwt.utils.JWTUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：qs
 * @date ：Created in 2022/3/20
 * @description：
 * @modified By：
 */
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();

        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //获取请求的方法
        HandlerMethod handlerMethod=(HandlerMethod)handler;
        Method method=handlerMethod.getMethod();

        //检查是否有passtoken注释，有则跳过认证
//        if (method.isAnnotationPresent(PassToken.class)) {
//            PassToken passToken = method.getAnnotation(PassToken.class);
//            if (passToken.required()) {
//                return true;
//            }
//        }

        // 获取请求头中的令牌
        String token = request.getHeader("token");
        try {
            // 验证令牌
            JWTUtils.verify(token);
            // 验证成功后直接返回true
            return true;
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("msg", "签名异常～");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            map.put("msg", "token异常～");
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            map.put("msg", "算法异常～");
        } catch (Exception e){
            e.printStackTrace();
            map.put("msg", "未知异常～");
        }
        map.put("state", false);
        // 将map转为json jackson
        String json = new ObjectMapper().writeValueAsString(map);
        // 将map以json的方式写入response
        response.setContentType("application/json;charset-UTF-8");
        response.getWriter().println(json);
        return false;
    }
}
